import os
from pathlib import Path
import codecs

import rock_hammer as rh


here_path = Path(os.path.dirname(__file__)).absolute()
os.chdir(here_path)

here_dir_name = here_path.name
prj_files = list(here_path.glob('*.prj'))
if len(prj_files) != 1:
    print(rh.red(f'-!> 必须有一个.prj 文件，找到了{len(prj_files)} 个'))
    
prj_path = prj_files[0]
ini_path = here_path / rh.change_file_name_extension(prj_path.name, '.ini')

new_prj_path = prj_path.rename(here_path / (here_dir_name + '.prj'))
new_ini_path = ini_path.rename(here_path / (here_dir_name + '.ini'))

d = rh.data_load_from_ini(new_prj_path, 'utf-16')
d['Projece Name'] = new_prj_path.name
d['Projece Path'] = str(new_prj_path.absolute())

c_list = [f.name for f in here_path.glob('*.c')]
h_list = [f.name for f in here_path.glob('*.h')]

d['Source File'] = ','.join(c_list) + ','
d['Head File 00'] = ','.join(h_list)
rh.data_store_to_ini(d, new_prj_path, 'utf-8')

with open(new_prj_path, 'r', encoding='utf-8') as f:
    text = f.read()

with open(new_prj_path, 'w', encoding='utf-16-le') as f:
    f.write(text.strip())
    f.write('\n\n')

rh.add_header_to_file(new_prj_path, codecs.BOM_UTF16_LE)


os.system('pause')